<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
    <div class="max-w-2xl mx-auto px-4">
      <div v-if="loading" class="text-center py-12">
        <Icon name="line-md:loading-loop" class="w-12 h-12 text-blue-600 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">正在生成支付...</p>
      </div>

      <div v-else-if="paymentInfo" class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8">
        <!-- 微信Native支付（二维码） -->
        <div v-if="paymentMethod === 'wechat_native'" class="text-center">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">微信支付</h2>
          <p class="text-gray-600 dark:text-gray-400 mb-6">请使用微信扫描二维码完成支付</p>

          <div class="inline-block p-4 bg-white rounded-lg qrcode-container">
            <img ref="qrcodeRef" class="w-64 h-64" alt="支付二维码" />
          </div>

          <div class="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
            <p class="text-sm text-gray-600 dark:text-gray-400">
              订单号：{{ order.orderNo }}
            </p>
            <p class="text-2xl font-bold text-blue-600 mt-2">
              ¥{{ order.totalPrice }}
            </p>
          </div>

          <div class="mt-6">
            <div v-if="checking" class="flex items-center justify-center gap-2 text-blue-600">
              <Icon name="line-md:loading-loop" class="w-5 h-5" />
              <span>等待支付中...</span>
            </div>
            <div v-if="expired" class="text-red-600">
              <Icon name="heroicons:exclamation-circle" class="w-6 h-6 mx-auto mb-2" />
              <p>二维码已过期，请重新创建订单</p>
            </div>
          </div>
        </div>

        <!-- 支付宝支付（跳转） -->
        <div v-else-if="paymentMethod === 'alipay_page' || paymentMethod === 'alipay_wap'" class="text-center">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">支付宝支付</h2>
          <p class="text-gray-600 dark:text-gray-400 mb-6">即将跳转到支付宝...</p>

          <div class="mt-6">
            <Icon name="ri:alipay-fill" class="w-24 h-24 text-blue-600 mx-auto" />
          </div>

          <p class="mt-6 text-sm text-gray-500 dark:text-gray-400">
            如果没有自动跳转，请点击下方按钮
          </p>
          <button
            @click="redirectToAlipay"
            class="mt-4 px-8 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            前往支付宝支付
          </button>
        </div>

        <!-- 返回按钮 -->
        <div class="mt-8 text-center">
          <button
            @click="goBack"
            class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
          >
            ← 返回订单页面
          </button>
        </div>
      </div>

      <div v-else class="text-center py-12">
        <Icon name="heroicons:exclamation-circle" class="w-16 h-16 text-red-500 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">支付创建失败</p>
        <button
          @click="goBack"
          class="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          返回
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import QRCode from 'qrcode'

const route = useRoute()
const router = useRouter()
const $api = useNuxtApp().$api
const toast = useToast()

const order = ref<any>(null)
const paymentInfo = ref<any>(null)
const loading = ref(true)
const checking = ref(false)
const expired = ref(false)
const qrcodeRef = ref<HTMLImageElement | null>(null)
const paymentMethod = ref<string>('')

let checkInterval: NodeJS.Timeout | null = null

onMounted(async () => {
  const orderId = route.params.id
  paymentMethod.value = route.query.method as string || 'wechat_native'

  try {
    // 获取订单信息
    order.value = await $api(`/orders/${orderId}`) as any
    console.log('📦 订单信息:', order.value)

    // 创建支付
    paymentInfo.value = await $api('/payment/create', {
      method: 'POST',
      body: {
        orderId: parseInt(orderId as string),
        amount: order.value.totalPrice,
        paymentMethod: paymentMethod.value
      }
    }) as any
    
    console.log('💳 支付信息:', paymentInfo.value)

    // 处理不同支付方式
    if (paymentMethod.value === 'wechat_native' && paymentInfo.value.codeUrl) {
      // 等待 DOM 更新（需要多次 nextTick 确保条件渲染完成）
      await nextTick()
      await nextTick()
      
      // 使用 setTimeout 确保 DOM 完全渲染
      setTimeout(async () => {
        if (qrcodeRef.value) {
          console.log('🔍 生成二维码:', paymentInfo.value.codeUrl)
          try {
            const url = await QRCode.toDataURL(paymentInfo.value.codeUrl, {
              width: 256,
              margin: 1,
              color: {
                dark: '#000000',
                light: '#FFFFFF'
              }
            })
            if (qrcodeRef.value) {
              qrcodeRef.value.src = url
              console.log('✅ 二维码生成成功')
            }
          } catch (err) {
            console.error('❌ 二维码生成失败:', err)
            toast.error('二维码生成失败')
          }
        } else {
          console.error('❌ qrcodeRef 不存在，尝试直接创建二维码')
          // 作为备用方案，直接创建一个 canvas 元素
          const container = document.querySelector('.qrcode-container')
          if (container) {
            const canvas = document.createElement('canvas')
            await QRCode.toCanvas(canvas, paymentInfo.value.codeUrl, {
              width: 256,
              margin: 1
            })
            container.innerHTML = ''
            container.appendChild(canvas)
            console.log('✅ 使用备用方案生成二维码成功')
          }
        }
      }, 100)

      // 开始轮询支付状态
      startCheckPayment()
    } else if (paymentMethod.value.startsWith('alipay') && paymentInfo.value.payUrl) {
      // 支付宝支付，跳转
      toast.info('即将跳转到支付宝...')
      setTimeout(() => {
        redirectToAlipay()
      }, 2000)
    }
  } catch (error: any) {
    console.error('❌ 创建支付失败:', error)
    toast.error(error?.data?.message || '创建支付失败，请重试')
  } finally {
    loading.value = false
  }
})

onUnmounted(() => {
  if (checkInterval) {
    clearInterval(checkInterval)
  }
})

// 轮询检查支付状态
const startCheckPayment = () => {
  checking.value = true
  let count = 0
  const maxCount = 60 // 最多检查5分钟（60次 x 3秒 = 3分钟）

  console.log('🔄 开始轮询支付状态...')
  console.log('📦 订单号:', order.value.orderNo)
  console.log('💳 支付方式:', paymentMethod.value)

  checkInterval = setInterval(async () => {
    count++
    const currentTime = new Date().toLocaleTimeString()
    
    console.log(`\n========== 🔍 第 ${count} 次查询支付状态 ==========`)
    console.log('⏰ 时间:', currentTime)
    
    if (count > maxCount) {
      console.warn('⏱️ 超时：已查询', maxCount, '次，停止轮询')
      clearInterval(checkInterval!)
      expired.value = true
      checking.value = false
      toast.error('支付二维码已过期，请重新创建订单')
      return
    }

    try {
      const result = await $api(`/payment/query/${order.value.orderNo}?method=${paymentMethod.value}`) as any
      
      console.log('📱 查询结果:', result)
      console.log('支付状态:', {
        微信状态: result.trade_state,
        支付宝状态: result.tradeStatus,
        订单号: result.out_trade_no,
        交易号: result.transaction_id,
      })
      
      // 检查是否支付成功
      const isSuccess = result.trade_state === 'SUCCESS' || 
                       result.tradeStatus === 'TRADE_SUCCESS' ||
                       result.tradeStatus === 'TRADE_FINISHED'
      
      if (isSuccess) {
        console.log('🎉 支付成功！')
        console.log('========== ✅ 停止轮询，跳转结果页 ==========\n')
        
        clearInterval(checkInterval!)
        checking.value = false
        
        // 显示成功提示
        toast.success('支付成功！正在跳转...')
        
        // 延迟1秒后跳转，让用户看到成功提示
        setTimeout(() => {
          router.push(`/order/result?orderNo=${order.value.orderNo}&status=success`)
        }, 1000)
      } else {
        console.log('⏳ 等待支付中...')
        console.log('========== ⏳ 继续等待 ==========\n')
      }
    } catch (error: any) {
      console.error('========== ❌ 查询失败 ==========')
      console.error('错误:', error)
      console.error('错误详情:', error?.data || error?.message)
      console.error('========== ❌ 错误结束 ==========\n')
      
      // 查询失败不影响轮询，继续下一次
    }
  }, 3000) // 每3秒查询一次
}

// 跳转到支付宝
const redirectToAlipay = () => {
  if (paymentInfo.value?.payUrl) {
    // 直接渲染支付宝form
    const div = document.createElement('div')
    div.innerHTML = paymentInfo.value.payUrl
    document.body.appendChild(div)
    const form = div.querySelector('form')
    if (form) {
      form.submit()
    }
  }
}

const goBack = () => {
  router.back()
}
</script>




